from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from ft_table import FtTable
from testing import get_request
import datetime, os,logging

PAGE_SIZE = 15



def process_records(records, report_date):
    '''
    records are testing records
    process the records for reporing
    return
     {
       projects: [
         {
             project_number: ,
                client_name: , 
                       date: ,
                       rows: [
                               {
                                   actual testing records, ordered by report_test_no
                               }
                       
                       ]
             
         }
       
       ]
    }
    '''
    
    #use a dictionary to group records by project number
    projects = {}
    
    for record in records:
        project_number = record['project_number']
        if projects.setdefault(project_number, {}):
            pass
        else:
            #it is the first record
            project = projects[project_number]
            for fld in ['client_name', 'project_name', 'project_number']:
                project[fld] = record[fld]
            
            project['date'] = report_date
            project['rows'] = []
        projects[project_number]['rows'].append(record)
        
    def keyFn(k):
        #sort by report_test_no and test_no
        try:
            v = float(k['report_test_no'])
        except:
            try:
                v = float(k['test_no'])
            except: 
                v = 0
        return v
    
    #sort rows for each project
    for k in projects.keys():
        projects[k]['rows'] = sorted(projects[k]['rows'], key=keyFn)
    
    results = []
    for pn in projects.keys():
        results.append(projects[pn])
    
    return {'projects': results}
        
    
    
class ReportHandler(webapp.RequestHandler):
    def get(self):
        self.post()
        
    
    def post(self):
        #reuse the testing get_rquest to build the request data
        request = get_request(self.request)
        request['limit'] = ''
        request['start'] = ''
        
        ft = FtTable(None, None, request['tableid'])
        #get the current date
        datevalue = datetime.datetime.now()
        datevalue = '%2d/%2d/%4d' % (datevalue.month,datevalue.day,datevalue.year)
        #query results 
        results = ft.get_records(request, True)
        #process the results
        data = process_records(results, datevalue)
        #add query summary data
        data['query_time'] = datetime.datetime.now()
        data['query_from_date'] = request['from_dt'] or 'Not Defined'
        data['query_to_date'] = request['to_dt'] or 'Not Defined'
        data['client_name'] = request['client_name'] or 'Not Defined'
        data['project_name'] = request['project_name'] or 'Not Defined'
        data['testing_type'] = request['testing_type'] or 'Not Defined'
        data['PARENT_RECORD_ID'] = request['PARENT_RECORD_ID'] or 'Not Defined'
        data['count'] = len(results)
        #generate the report
        self.project_report(data)
       
    def project_report(self, data):
        '''
        generate the report
        '''
        #build tables, each table has 15 rows
        table = []
        for project in data['projects']:
            
            project.setdefault('tables', [])
            i = 0
            for record in project['rows']:
                i = i + 1
                row = record
                if i%2==1: 
                    row['class'] = 'odd'
                else:
                    row['class'] = 'even'
                for fld in 'wet_unit_weight    moisture_content    dry_unit_weight    moisture_contentlab    dry_unit_weight_lab    max_dry_unit_weight    optimum_moisture_content    specified    obtained'.split():
                    v = row.get(fld)
                    if v:
                        row[fld] = '%.1f' % float(v)
                        logging.info('%s: %s' % (fld, row[fld]))
                row['remarks'] = row['remarks'].replace('_', ' ').title() 
                table.append(row) 
                if i>PAGE_SIZE-1:
                    project['tables'].append(table)
                    table = []
                    i = 0
            if i<=PAGE_SIZE-1:
                project['tables'].append(table)
                
        path = os.path.join(os.path.dirname(__file__), 'template/report_tmp.html')
        self.response.out.write(template.render(path, data))
            
            
